import mapboxgl from 'mapbox-gl'
import { onMounted, onUnmounted, reactive } from 'vue'
import baseMap from '@/components/mapbox/const.js'

const useMapboxGl = () => {
	mapboxgl.accessToken = import.meta.env.VITE_APP_MAPBOX_TOKEN

	// 初始化地图
	onMounted(() => {
		window.map = new mapboxgl.Map({
			container: 'map',
		})
		baseMap.layers.forEach((item) => {
			addLayers(item)
		})
	})

	onUnmounted(() => {
		window.map.off('mousemove')
		window.map.remove()
		window.map = null
	})

	// 监听鼠标位置 获取当前坐标
	const lngLat = reactive({
		lng: 0,
		lat: 0,
	})
	const mousePosition = () => {
		window.map.on('mousemove', (event) => {
			const { lng, lat } = event.lngLat
			Object.assign(lngLat, { lat, lng })
		})
	}

	// 添加图层
	const addLayers = (item) => {
		window.map.addLayer({
			id: item.id,
			type: 'raster',
			source: {
				type: 'raster',
				tiles: [item.url],
			},
			layout: {
				visibility: item.visibility || 'none',
			},
		})
	}

	// 设置图层显示隐藏
	const visibleLayer = (id, visible) => {
		window.map.setLayoutProperty(id, 'visibility', visible)
	}

	return {
		lngLat,
		addLayers,
		visibleLayer,
		mousePosition,
	}
}

export default useMapboxGl
